import { ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {useGetPersonalInfo} from "@/api/getPersonalInfo";
import {useGetUserInfoInCard} from "@/api/getUserInfoInCard";
import {useGetTaskRecordBySender} from "@/api/getTaskRecordsBySender";
import {useGetTaskRecordByReceiver} from "@/api/getTaskRecordsByReceiver";
/**
 * 验证码登录请求
 * @returns { handleMsgLogin, phoneNumber, code, isLoading }
 */
export function msgLogin() {
    const phoneNumberVerify2 = ref(""); // 手机号
    const verificationCode = ref(""); // 验证码
    const isLoading = ref(false); // 加载状态

    const store = useStore(); // 获取 Vuex Store 实例
    const router = useRouter(); // 获取 Vue Router 实例
    // 获取 handleGetPersonalInfo 方法
    const { handleGetPersonalInfo } = useGetPersonalInfo();
    const { handleGetUserInfoInCard } = useGetUserInfoInCard();
    const { handleGetTaskRecordByReceiver } = useGetTaskRecordByReceiver();
    const { handleGetTaskRecordBySender } = useGetTaskRecordBySender();
    // 处理验证码登录
    const handleMsgLogin = async () => {
        // 简单的表单验证
        if (!phoneNumberVerify2.value || !verificationCode.value) {
            alert("请输入手机号和验证码");
            return;
        }

        isLoading.value = true; // 设置加载状态为 true

        try {
            // 调用 Vuex 中的 loginByMsg action
            const response = await store.dispatch("loginByMsg", {
                phoneNumber: phoneNumberVerify2.value,
                code: verificationCode.value,
            });
            if (response.success) {
                alert("登录成功");
                if(!response.data){
                    // 获取用户个人信息
                    await handleGetPersonalInfo();
                    await handleGetUserInfoInCard();
                    await handleGetTaskRecordByReceiver();
                    await handleGetTaskRecordBySender();
                    router.push("/home"); // 跳转到首页
                }
                else {
                    router.push("/complete-info"); // 跳转到完善信息页
                }
            } else {
                alert(response.message || "登录失败");
            }
        } catch (error) {
            console.error("登录错误:", error);
            alert("登录失败，请检查网络或稍后再试");
        } finally {
            isLoading.value = false; // 重置加载状态
        }
    };

    return {
        handleMsgLogin,
        phoneNumberVerify2,
        verificationCode,
        isLoading,
    };
}
